<?php
namespace app\channel\controller;
use think\Db;

class GameList extends Base
{
    //只有CPS渠道可以访问
    public function _initialize(){
        parent::_initialize();
        if(!session('admin.cps_id')){
            $this->error('访问错误');
        }
    }

    public function index(){
        if(request()->isAjax()) {
            $gameId = input('game_id');
            $page = input('page');
            $limit = input('limit');
            $appClassId = input('app_class_id');
            $appPublishTypeId = input('app_publish_type_id');
            $appPlatformTypeId = input('app_platform_type_id');

            $where = 1;
            //是自有渠道，显示所有游戏
            session('admin.cps_id')!=1000 && $where .= " && status=1";

            //如果不是自有工会，不显示1297游戏，如果是自有工会，只显示1297游戏

            $channelStr1 = model('manage/Channel')->allChannelId(2161);
            $channelArr1 = explode(',', $channelStr1);
//            $channelStr2 = model('manage/Channel')->allChannelId(2064);
//            $channelArr2 = explode(',', $channelStr2);
//            $channelStr3 = model('manage/Channel')->allChannelId(2065);
//            $channelArr3 = explode(',', $channelStr3);
//            $channelStr4 = model('manage/Channel')->allChannelId(2067);
//            $channelArr4 = explode(',', $channelStr4);
            $channelArr = array_merge($channelArr1);
            if( !in_array(session('admin.cps_id'), $channelArr)){
                $where .= " && game_id<>1402";
            }else{
                $where .= " && game_id=1402";
            }

            !empty($gameId) && $where .= " && game_id={$gameId}";
            !empty($appClassId) && $where .= " && app_class_id={$appClassId}";
            !empty($appPublishTypeId) && $where .= " && app_publish_type_id={$appPublishTypeId}";
            !empty($appPlatformTypeId) && $where .= " && app_platform_type_id={$appPlatformTypeId}";

            if (!$count = Db::name('ViewGameManage')->where($where)->count()) {
                $this->layTable();
            }

            $select = Db::name('ViewGameManage')
                ->where($where)
                ->limit(($page-1)*$limit, $limit)
                ->order('left(online_time_region, 10) desc')
                ->select();

            $data = [];
            $appClassIdName = changeValKey('AppClass', 'id', 'name');
            $appPublishIdName = changeValKey('AppPublishType', 'id', 'name');
            $packProcess = config('pack_process');

            $select2 = Db::name('ChannelGame')->field('game_id, download, status, msg')->where('channel_id', session('admin.cps_id'))->select();
            $channelGame = [];
            foreach ($select2 as $k=>$v){
                $channelGame[$v['game_id']] = [
                    'download' => $v['download'],
                    'status' => $v['status'],
                    'msg' => $v['msg'],
                ];
            }


            foreach ($select as $k => $v) {
                $download = '';
                if($v['app_client_type_id']==4){ //如果是h5直链
                    if($v['game_id']>=1246){
                        $download = 'http://h.miyuhaiwai.com/home?gameId='.$v['game_id'].'&channelId=1000&cpsId='.session('admin.cps_id');
                    }else{
                        $download = 'http://h5.miyuhaiwai.com/?gameId='.$v['game_id'].'&channelId='.session('admin.cps_id');
                    }
                }
                if(isset($channelGame[$v['game_id']]['download'])){ //如果已打包
                    $download = $channelGame[$v['game_id']]['download'];
                }

                $data[] = [
                    'icon' => '<img src="'.$v['icon'].'" alt="" width="50" height="50">',
                    'game_id' => $v['game_id'],
                    'game_name' => $v['game_name'],
                    'app_class_id' => isset($appClassIdName[ $v['app_class_id'] ]) ? $appClassIdName[ $v['app_class_id'] ] : '',
                    'app_publish_type_id' => isset($appPublishIdName[ $v['app_publish_type_id'] ]) ? $appPublishIdName[ $v['app_publish_type_id'] ] : '',
                    'package_size' => round(($v['package_size'])/(1024*1024),2) . 'MB',
                    'version_str' => $v['version_str'],
                    'online_time_region' => explodeGameTime($v['online_time_region']),
                    'download' => $download,
                    'status' => isset($channelGame[$v['game_id']]['status']) ? $channelGame[$v['game_id']]['status'] : '',
                    'msg' => isset($channelGame[$v['game_id']]['msg']) ? $channelGame[$v['game_id']]['msg'] : '',
                    'app_client_type_id' => $v['app_client_type_id'],
                ];
            }

            $this->layTable(0, '游戏列表', $data, $count);
        }else{
            $appClassId = Db::name('AppClass')->select();
            $appPublishTypeId = Db::name('AppPublishType')->select();
            $appPlatformTypeId = Db::name('AppPlatformType')->select();
            $gameId = Db::name('ViewGameManage')->field('game_id, game_name')->where('status', 1)->order('game_id desc')->select();

            return view('', ['game_id'=>$gameId, 'app_class_id' => $appClassId, 'app_publish_type_id' => $appPublishTypeId, 'app_platform_type_id'=>$appPlatformTypeId]);
        }
    }

    //打包
    public function pack(){
        //获取打包参数
        $gameId = input('game_id');

        $game = Db::name('ViewGameManage')->where('game_id', $gameId)->find();

        $unpackPath = ROOT_PATH.'/uploads/apk/unpack/'.$gameId;//要分包的解包文件目录
        if(!file_exists($unpackPath.'/AndroidManifest.xml')){
            $this->layJson(1, '没有找到母包,请联系客服处理');
        }

        //查询该渠道用户是否已经申请过打包该游戏
        $whereChannel['channel_id'] = session('admin.cps_id');
        $whereChannel['game_id'] = $gameId;
        $channel = Db::name('ChannelGame')->where($whereChannel)->find();

        if($channel){
            $updateChannel['download'] = '';
            $updateChannel['addtime'] = time();
            $updateChannel['status'] = 0;
            $updateChannel['msg'] = '排队中';
            $updateChannel['packcount'] = 0;
            $updateChannel['storage'] = $game['up_location'];
            $updateChannel['version'] = '';
            Db::name('ChannelGame')->where($whereChannel)->update($updateChannel);
        }else{
            //没有打包过就保存打包的游戏数据
            $insertChannel['account_id'] = '';
            $insertChannel['channel_id'] = session('admin.cps_id');
            $insertChannel['game_id'] = $gameId;
            $insertChannel['download'] = '';
            $insertChannel['addtime'] = time();
            $insertChannel['status'] = 0;
            $insertChannel['msg'] = '排队中';
            $insertChannel['packcount'] = 0;
            $insertChannel['storage'] = $game['up_location'];
            $insertChannel['version'] = '';
            $insertRs = Db::name('ChannelGame')->insert($insertChannel);
            if(empty($insertRs)){
                $this->layJson(1, '申请打包异常，请重新申请');
            }
        }

        $cmd="/data/apk/shell/packcontroller.sh";
        @shell_exec("$cmd > /dev/null 2>&1 &");
        $this->layJson(0, '已加入打包队列,刷新此页面可查看当前打包状态');
    }
}
